package org.ojudge.ojudgecodesandbox.sandbox;

import cn.hutool.core.date.StopWatch;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.*;
import com.github.dockerjava.api.model.*;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.core.command.ExecStartResultCallback;
import lombok.extern.slf4j.Slf4j;
import org.ojudge.ojudgecodesandbox.modal.ExecuteCodeRequest;
import org.ojudge.ojudgecodesandbox.modal.ExecuteCodeResponse;
import org.ojudge.ojudgecodesandbox.modal.ExecuteMessage;
import org.ojudge.ojudgecodesandbox.modal.JudgeInfo;
import org.ojudge.ojudgecodesandbox.utils.ProcessUtils;

import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * Docker中的代码沙箱
 */
@Slf4j
public class JavaDockerCodeSandbox implements CodeSandbox {

    private static final String GLOBAL_CODE_PATH = "tempCode";

    private static final String GLOBAL_JAVA_CLASS_PATH = "Main.java";
    private static final long TIME_OUT = 5000;
    private static final String SECURITY_MANAGER_PATH = "E:\\Programme\\Code\\Project\\oJudge\\oJudge-code-sandbox\\src\\main\\resources\\security\\MySecurityManager.class";
    private static final String SECURITY_MANAGER_CLASS_NAME = "MySecurityManager";
    private static Boolean FIRST_INIT = false;

    public static void main(String[] args) {
        JavaDockerCodeSandbox javaNativeCodeSandbox = new JavaDockerCodeSandbox();
//        String code = ResourceUtil.readStr("testCode/simpleComputeArgs/Main.java", StandardCharsets.UTF_8);
        String code = ResourceUtil.readStr("testCode/simpleComputeArgs/Main.java", StandardCharsets.UTF_8);
        ExecuteCodeRequest request = new ExecuteCodeRequest();
        request.setInputList(Arrays.asList("1 2", "2 3"));
        request.setCode(code);
        request.setLanguage("java");
        ExecuteCodeResponse executeCodeResponse = javaNativeCodeSandbox.executeCode(request);
        System.out.println(executeCodeResponse);
    }

    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest request) {
//        System.setSecurityManager(new DefaultSecurityManager());

        List<String> inputList = request.getInputList();
        String code = request.getCode();
        String language = request.getLanguage();

        String userDir = System.getProperty("user.dir");
        String globalCodePathName = userDir + File.separator + GLOBAL_CODE_PATH;//注意使用File.separator保证不同操作系统环境同样能运行
        //判断全局代码目录是否存在,没有就新建
        if (!FileUtil.exist(globalCodePathName)) {
            FileUtil.mkdir(globalCodePathName);
        }

        // 1.把用户的代码隔离存放为文件
        String userCodeParentPath = globalCodePathName + File.separator + UUID.randomUUID();
        String userCodePath = userCodeParentPath + File.separator + GLOBAL_JAVA_CLASS_PATH;
        File userCodeFile = FileUtil.writeString(code, userCodePath, StandardCharsets.UTF_8);

        // 2.编译代码
        String compileCmd = String.format("javac -encoding utf-8 %s", userCodeFile.getAbsolutePath());
        try {
            Process compileProcess = Runtime.getRuntime().exec(compileCmd);
            ExecuteMessage executeMessage = ProcessUtils.runProcess(compileProcess, "编译");
            System.out.println(executeMessage);
        } catch (IOException e) {
            System.out.println("编译错误");
        }

        // 3.创建容器,把文件复制到容器内

        //获取默认的DockerClient
        DockerClient dockerClient = DockerClientBuilder.getInstance().build();


        //拉取镜像
        String image = "openjdk:8-alpine";
        if (FIRST_INIT) {
            PullImageCmd pullImageCmd = dockerClient.pullImageCmd(image);
            PullImageResultCallback callback = new PullImageResultCallback() {
                @Override
                public void onNext(PullResponseItem item) {
                    System.out.println("下载镜像：" + item.getStatus());
                    super.onNext(item);
                }
            };
            try {
                pullImageCmd.exec(callback).awaitCompletion();
            } catch (InterruptedException e) {
                log.error("拉取镜像失败");
                return null;
            }
            FIRST_INIT = false;
            log.info("下载镜像:{}", image);
        }

        //创建容器

        CreateContainerCmd createContainerCmd = dockerClient.createContainerCmd(image);
        HostConfig hostConfig = new HostConfig();
        hostConfig.setBinds(new Bind(userCodeParentPath, new Volume("/app")));//绑定挂载,用于同步文件内容
        hostConfig.withMemory(100 * 1024 * 1024L);
        hostConfig.withMemorySwap(0L);
        hostConfig.withCpuCount(1L);
        hostConfig.withReadonlyRootfs(true);
        hostConfig.withSecurityOpts(Arrays.asList("seccomp=安全管理配置字符串"));


        CreateContainerResponse createContainerResponse = createContainerCmd
                .withNetworkDisabled(true)
                .withHostConfig(hostConfig)
                .withAttachStdin(true)
                .withAttachStdout(true)
                .withAttachStderr(true)
                .withTty(true) //启动之后容器可以一直存在,不会退出
                .exec();
        String containerId = createContainerResponse.getId();
        System.out.println("容器创建成功：" + containerId);

        //启动容器
        dockerClient.startContainerCmd(containerId).exec();

        List<ExecuteMessage> executeMessageList = new ArrayList<>();

        // docker exec exciting_kapitsa java -cp ./app Main 1 3
        for (String inputArgs : inputList) {
            StopWatch stopWatch = new StopWatch(); // 创建计时器
            String[] inputArgsArray = inputArgs.split(" ");// 把输入参数转换成数组
            String[] cmdArray = ArrayUtil.append(new String[]{"java", "-cp", "/app", "Main"}, inputArgsArray);// 创建命令
            long time;
            ExecCreateCmdResponse execCreateCmdResponse = dockerClient.execCreateCmd(containerId)
                    .withCmd(cmdArray)
                    .withAttachStderr(true)
                    .withAttachStdin(true)
                    .withAttachStdout(true)
                    .exec();
            log.info("创建执行命令:{}", execCreateCmdResponse);

            ExecuteMessage executeMessage = new ExecuteMessage();
            final String[] message = {null};
            final String[] errorMessage = {null};

            String execId = execCreateCmdResponse.getId();
            ExecStartResultCallback execStartResultCallback = new ExecStartResultCallback() {
                @Override
                public void onNext(Frame frame) {
                    StreamType streamType = frame.getStreamType();
                    if (StreamType.STDERR.equals(streamType)) {
                        errorMessage[0] = new String(frame.getPayload());
                        log.info("docker exec输出错误结果{}", errorMessage[0]);
                    } else {
                        message[0] = new String(frame.getPayload());
                        log.info("docker exec输出结果{}", message[0]);
                    }
                    super.onNext(frame);
                }
            };

            final long[] maxMemory = {0L};

            //获取内存
            StatsCmd statsCmd = dockerClient.statsCmd(containerId);
            ResultCallback<Statistics> statisticsResultCallback = new ResultCallback<Statistics>() {
                @Override
                public void onNext(Statistics statistics) {
                    Long memoryUsage = statistics.getMemoryStats().getUsage();
                    log.info("内存占用{}", memoryUsage);
                    maxMemory[0] = Math.max(maxMemory[0], memoryUsage != null ? memoryUsage : 0L);
                }
                @Override
                public void onStart(Closeable closeable) {}
                @Override
                public void onError(Throwable throwable) {}
                @Override
                public void onComplete() {}
                @Override
                public void close() {}
            };
            statsCmd.exec(statisticsResultCallback);

            //运行代码
            try {
                stopWatch.start();
                boolean completion = dockerClient
                        .execStartCmd(execId)
                        .exec(execStartResultCallback)
                        .awaitCompletion(TIME_OUT, TimeUnit.MILLISECONDS);
                if (!completion) {
                    log.error("执行超时");
                    executeMessage.setExitValue(-1);
                    executeMessage.setMessage("代码执行超时");
                    executeMessage.setErrorMessage("代码执行超时");
                    executeMessage.setTime(TIME_OUT);
                    executeMessage.setMemory(0L);
                    executeMessageList.add(executeMessage);
                    continue;
                }
                stopWatch.stop();
                time = stopWatch.getLastTaskTimeMillis();
                statsCmd.close();
            } catch (InterruptedException e) {
                log.error("执行错误{}", e.getMessage());
                throw new RuntimeException(e);
            }
            executeMessage.setErrorMessage(errorMessage[0]);
            executeMessage.setMessage(message[0]);
            executeMessage.setTime(time);
            executeMessage.setMemory(maxMemory[0]);
            log.info("执行结果{}", executeMessage);
            executeMessageList.add(executeMessage);
        }


        //收集整理输出结果
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        List<String> outputList = new ArrayList<>();
        //取用时最大值,便于判断是否超时
        long maxTime = 0;
        for (ExecuteMessage executeMessage : executeMessageList) {
            String errorMessage = executeMessage.getErrorMessage();
            if (StrUtil.isNotBlank(errorMessage)) {
                executeCodeResponse.setMessage(errorMessage);
                //执行中存在错误
                executeCodeResponse.setStatus(3);
                break;
            }
            outputList.add(executeMessage.getMessage());
            Long time = executeMessage.getTime();
            if (time != null) {
                maxTime = Math.max(maxTime, time);
            }
        }
        //正常运行完成
        if (outputList.size() == executeMessageList.size()) {
            executeCodeResponse.setStatus(1);
        }
        executeCodeResponse.setOutputList(outputList);
        executeCodeResponse.setStatus(1);
        JudgeInfo judgeInfo = new JudgeInfo();
        judgeInfo.setTime(maxTime);

        executeCodeResponse.setJudgeInfo(judgeInfo);

        //删除文件
        if (userCodeFile.getParent() != null) {
            boolean del = FileUtil.del(userCodeFile.getParent());
            log.info("程序运行完成,删除文件{}", (del ? "成功" : "失败"));
        }
        return executeCodeResponse;
    }

    /**
     * 获取错误响应
     *
     * @param e
     * @return
     */
    private ExecuteCodeResponse getErrorResponse(Throwable e) {
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        executeCodeResponse.setOutputList(new ArrayList<>());
        executeCodeResponse.setMessage(e.getMessage());
        executeCodeResponse.setStatus(2);//表示代码沙箱错误
        executeCodeResponse.setJudgeInfo(new JudgeInfo());
        return executeCodeResponse;

    }
}
